package day21;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;


/**
 * PipedStreamDemo.java
 * @author wangbiao
 *         email:785497344@qq.com
 * @Description 管道流：和多线程相关联的流对象
 * @since 1.0.0
 * @Date 2013-6-29上午11:26:48
 */
public class PipedStreamDemo {

	public static void main(String[] args) {
		PipedInputStream in = new PipedInputStream();
		PipedOutputStream out = new PipedOutputStream();
		try {
			in.connect(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
		new Thread(new Read(in)).start();
		new Thread(new Write(out)).start();
	}
}

class Read implements Runnable {

	private PipedInputStream in;
	
	
	public Read(PipedInputStream in) {
		super();
		this.in = in;
	}


	@Override
	public void run() {
		byte[] buf = new byte[1024];
		try {
			int len = in.read(buf);
			String str = new String(buf,0,len);
			System.out.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}

class Write implements Runnable {

	private PipedOutputStream out;
	
	public Write(PipedOutputStream out) {
		super();
		this.out = out;
	}

	@Override
	public void run() {
		try {
			out.write("piped is write".getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
